package model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import javax.swing.AbstractListModel;

import domain.Book;
import domain.Copy;
import domain.Library;

public class CopyListModel extends AbstractListModel<Copy> implements Observer {

    private static HashMap<Book, CopyListModel> instance = new HashMap<Book, CopyListModel>();

    public static CopyListModel getInstance(Book book) {
        if (!instance.containsKey(book)) {
            instance.put(book, new CopyListModel(book));
        }
        return instance.get(book);
    }

    List<Copy> model;
    final Book book;
    private static final long serialVersionUID = 2966279676059941187L;

    private CopyListModel(Book book) {
        if (book != null)
            book.addObserver(this);
        this.book = book;
        this.update(null, null);
    }

    @Override
    public Copy getElementAt(int index) {
        try {
            return model.get(index);
        } catch (IndexOutOfBoundsException e) {
            throw new ArrayIndexOutOfBoundsException(e.getMessage());
        }
    }

    @Override
    public void update(Observable o, Object arg) {
        model = book != null ? Library.getInstance().getCopiesOfBook(book) : new ArrayList<Copy>();
        this.fireContentsChanged(this, 0, model.size() - 1);
    }

    @Override
    public int getSize() {
        return model.size();
    }
}
